package com.example.demofx.master;

import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import java.util.List;
import java.util.stream.Collectors;

public class SidebarCreator {
    private ContactManager contactManager;
    private GroupManager groupManager;
    private ObservableList<Contact> contacts;
    private ListView<String> groupList;
    private ListView<String> contactList;
    private TitledPane groupsPane;
    private GroupChangedListener groupChangedListener;

    public SidebarCreator(ContactManager contactManager, GroupManager groupManager, GroupChangedListener groupChangedListener) {
        this.contactManager = contactManager;
        this.groupManager = groupManager;
        this.contacts = contactManager.getAllContacts();
        this.groupChangedListener = groupChangedListener;

        // 添加联系人列表变化监听器
        this.contacts.addListener((javafx.collections.ListChangeListener.Change<? extends Contact> change) -> {
            while (change.next()) {
                if (change.wasAdded() || change.wasRemoved() || change.wasUpdated()) {
                    updateGroupList();
                    updateContactList();
                }
            }
        });

        // 为每个 Contact 的 groups 添加监听器，同时更新联系人列表和分组列表
        contacts.forEach(contact -> {
            contact.getGroups().addListener((ListChangeListener<Group>) change -> {
                updateContactList(); // 更新联系人列表（所有联系人和未分组联系人）
                updateGroupList();   // 更新分组列表（各个组的联系人数量）
            });
        });
    }

    public VBox createSidebar() {
        VBox root = new VBox(10);
        root.setPadding(new Insets(10));
        root.setStyle("-fx-background-color: #6DD5ED;");

        TitledPane contactsPane = createContactsSection();
        groupsPane = createGroupsSection();

        root.getChildren().addAll(contactsPane, groupsPane);
        return root;
    }

    private TitledPane createContactsSection() {
        TitledPane contactsPane = new TitledPane("联系人", null);
        contactsPane.setExpanded(true);
        contactsPane.getStyleClass().add("contacts-pane");

        VBox contactsContent = new VBox(5);
        contactsContent.setPadding(new Insets(5));

        // 创建 contactList 来替代原来的 Label
        contactList = new ListView<>();
        contactList.getStyleClass().add("contact-list");
        contactList.setPrefHeight(2 * 24 + 2);
        updateContactList(); // 初始化列表项

        // 设置列表项的样式（可选）
        contactList.setCellFactory(param -> new ListCell<>() {
            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText(item);
                }
            }
        });

        contactsContent.getChildren().add(contactList);
        contactsPane.setContent(contactsContent);

        return contactsPane;
    }

    // 动态更新「联系人」列表项的数量
    public void updateContactList() {
        if (contactList != null) {
            contactList.getItems().clear();

            // 添加 "所有联系人"
            int allCount = contacts.size();
            contactList.getItems().add("所有联系人 (" + allCount + ")");

            // 获取未分组联系人数量
            List<Contact> ungroupedContacts = contactManager.getAllContacts().stream()
                    .filter(c -> c.getGroups().isEmpty())
                    .collect(Collectors.toList());
            contactList.getItems().add("未分组联系人 (" + ungroupedContacts.size() + ")");

        }
    }

    private TitledPane createGroupsSection() {
        TitledPane groupsPane = new TitledPane("分组", null);
        groupsPane.setExpanded(true);
        groupsPane.getStyleClass().add("groups-pane");

        VBox groupsContent = new VBox(5);
        groupsContent.setPadding(new Insets(5));

        groupList = new ListView<>();
        groupList.getStyleClass().add("group-list");
        updateGroupList();

        groupsContent.getChildren().add(groupList);
        groupsPane.setContent(groupsContent);

        return groupsPane;
    }

    public void updateGroupList() {
        this.contacts = contactManager.getAllContacts();

        if (groupList != null) {
            groupList.getItems().clear();

            // 普通分组
            for (Group group : groupManager.getGroups()) {
                int count = countContactsInGroup(group);
                groupList.getItems().add(group.getGroupName() + " (" + count + ")");
            }
        }
    }

    private int countContactsInGroup(Group targetGroup) {
        return (int) contacts.stream()
                .filter(contact -> contact.getGroups().contains(targetGroup))
                .count();
    }

    public void notifyGroupChanged() {
        if (groupChangedListener != null) {
            groupChangedListener.onGroupChanged();
        }
    }

    public String getSelectedGroupName() {
        return groupList.getSelectionModel().getSelectedItem();
    }

    // MainApp 可以访问到分组列表 groupList
    public ListView<String> getGroupList() {
        return groupList;
    }

    // MainApp 可以访问到分组列表 ContactList
    public ListView<String> getContactList() {
        return contactList;
    }
}